<template>
  <div class="app-container" ref="appContainer">
    <div class="conversion-table">
      <PropTable
        :columns="column"
        :data="list"
        :total="total"
        @reset="reset"
        @onSubmit="onSubmit"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
        @exportExcelAction="exportExcelAction"
      >
        <template v-slot:contractState="scope">
          <div v-if="!useEmpty(scope.row.contractState)">
            {{ scope.row.contractState === 0 ? "进行中" : "已完成" }}
          </div>
        </template>
        <!-- 业主单位 所在地区 行业 -->
        <template #otherSearch>
          <el-form-item label="业主单位" style="margin: 3px 3px 3px 0px">
            <el-input
              class="input-item"
              v-model="enterpriseName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <el-form-item label="合同金额" style="margin: 3px 3px 3px 0px">
            <el-input
              class="input-item"
              v-model="contractAmount"
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <el-form-item label="项目总投额" style="margin: 3px 3px 3px 0px">
            <el-input
              class="input-item"
              v-model="contractAllAmount"
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <el-form-item label="付款方式" style="margin: 3px 3px 3px 0px">
            <el-input
              class="input-item"
              v-model="paymentMethod"
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <el-form-item label="盖章份数" style="margin: 3px 3px 3px 0px">
            <el-input
              class="input-item"
              v-model="stampCount"
              placeholder="请输入"
            ></el-input>
          </el-form-item>

          <el-form-item label="盖章类型" style="margin: 3px 3px 3px 0px">
            <el-select
              v-model="stampTypeList"
              placeholder="请选择"
              multiple
              filterable
              allow-create
              default-first-option
              :reserve-keyword="false"
            >
              <el-option
                v-for="item in whatOptions"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="合同期限" style="margin: 3px 3px 3px 0px">
            <el-date-picker
              v-model="datetime"
              type="daterange"
              range-separator="至"
              start-placeholder="请选择"
              end-placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </template>

        <!-- 审批状态 -->
        <template v-slot:checkState="scope">
          <div v-if="!useEmpty(scope.row.checkState)">
            {{ getStatusLabel(scope.row.checkState) }}
          </div>
        </template>

        <template #btn>
          <div style="display: flex; justify-content: flex-end">
            <el-button type="primary" @click="handleAdd"
            v-if="userStore.rolescode!=15"
              ><el-icon><plus /></el-icon>新建合同</el-button>
          </div>
        </template>

        <template v-slot:operation="scope">
          <div style="display: flex; justify-content: flex-end">
            <el-button
              v-if="
                (scope.row.checkState === '0' || scope.row.checkState === '3')
                && userStore.rolescode!=15
              "
              link
              type="primary"
              icon="Edit"
              @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button
              v-if="scope.row.checkState !== '0' || userStore.rolescode==15 "
              link
              type="primary"
              icon="Edit"
              @click="handleDetails(scope.row)">
              详情
            </el-button>
            <el-button
              v-if="userStore.userId === 1 && userStore.rolescode!=15"
              link
              type="success"
              icon="Delete"
              @click="handelDelete(scope.row)">
              删除
            </el-button>
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handeleRevoke(scope.row)"
              v-if="scope.row.checkState === '2' && userStore.rolescode!=15">
              撤回
            </el-button>
            <!-- 审批 -->
            <el-button
              v-if="scope.row.checkState === '1' && userStore.rolescode!=15"
              link
              type="primary"
              icon="Edit"
              @click="handleFile(scope.row)">
              上传合同附件
            </el-button>
          </div>
        </template>
      </PropTable>
    </div>
  </div>
</template>
<script setup >
import { ref, reactive, onMounted, nextTick } from "vue";
//@ts-ignore
import PropTable from "@/components/Table/PropTable/index.vue";
//@ts-ignore
import { exportExcel } from "@/utils/exprotExcel";
import { useEmpty } from "@/utils/index";
import { ElMessageBox, ElMessage } from "element-plus";

import { useRouter, useRoute } from "vue-router";
import useUserStore from "@/store/modules/user";
import {
  contractListApi,
  contractDeleteApi,
  withdrawApi,
} from "@/api/contract/index";

const { proxy } = getCurrentInstance();

const loading = ref(true);
const detailsvisible = ref(false);
const userStore = useUserStore();

const route = useRoute();
const router = useRouter();

const businessoptions = ref([]);

const title = ref("");

// 搜素条件
const enterpriseName = ref();
const contractAmount = ref();
const contractAllAmount = ref();
const paymentMethod = ref();
const stampCount = ref();
const stampTypeList = ref();

const whatOptions = [
  {
    id: "1",
    label: "项目公章",
  },
  {
    id: "2",
    label: "项目财务章",
  },
  {
    id: "3",
    label: "成果章",
  },
  {
    id: "4",
    label: "许平人员章",
  },
  {
    id: "5",
    label: "赵冲人员章",
  },
  {
    id: "6",
    label: "牛天敏人员章",
  },
  {
    id: "7",
    label: "李彦文人员章",
  },
  {
    id: "8",
    label: "合同章",
  },
  {
    id: "9",
    label: "法人章",
  },
];

const optionsList = [
  {
    value: "2",
    label: "审批中",
  },
  {
    value: "1",
    label: "审批通过",
  },
  {
    value: "0",
    label: "审批驳回",
  },
  {
    value: "3",
    label: "审批撤回",
  },
];

const column = [
  {
    name: "projectName",
    label: "项目名称",
    inSearch: true,
    valueType: "input",
  },
  {
    name: "projecCode",
    label: "项目编号",
    inSearch: true,
    valueType: "input",
  },
  {
    name: "contractName",
    label: "合同名称",
  },

  {
    name: "checkState",
    label: "审批状态",
    inSearch: true,
    valueType: "select",
    options: optionsList,
    slot: true,
  },
  {
    name: "contractState",
    label: "合同状态",
    slot: true,
    // inSearch: true,
    // valueType: "input",
  },
  {
    name: "createTime",
    label: "创建时间",
  },
  { name: "operation", slot: true, fixed: "right", width: 350, label: "操作" },
];

const getStatusLabel = (value) => {
  let matchedOption = optionsList.find((option) => option.value === value);
  return matchedOption ? matchedOption.label : "";
};

const list = ref([]);

let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);

let paramsSubmit;
let datetime = ref();
let startTime = ref();
let endTime = ref();

const contract = async () => {
  if (datetime.value && datetime.value[0]) {
    startTime.value = datetime.value[0];
  }
  if (datetime.value && datetime.value[1]) {
    endTime.value = datetime.value[1];
  }

  if (datetime.value === null) {
    startTime.value = "";
    endTime.value = "";
  }

  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    startTime: startTime.value,
    endTime: endTime.value,
    enterpriseName: enterpriseName.value,
    contractAmount: contractAmount.value,
    contractAllAmount: contractAllAmount.value,
    paymentMethod: paymentMethod.value,
    stampCount: stampCount.value,
    stampTypeList: stampTypeList.value && stampTypeList.value.join(),
  };

  if (paramsSubmit) {
    for (let key in paramsSubmit) {
      if (paramsSubmit[key]) {
        params[key] = paramsSubmit[key];
      }
    }
  }

  const res = await contractListApi(params);
  if (res.code === 200) {
    list.value = res.rows;
    total.value = Number(res.total);
  } else {
    ElMessage.error(res.msg);
    // 进行提示
    loading.value = false;
  }
};

const reset = (val) => {
  val = "";
  (datetime.value = ""),
    (startTime.value = ""),
    (endTime.value = ""),
    (enterpriseName.value = ""),
    (contractAmount.value = ""),
    (contractAllAmount.value = ""),
    (paymentMethod.value = ""),
    (stampCount.value = ""),
    (stampTypeList.value = "");
  contract();
};

const onSubmit = (val) => {
  if (val) {
    paramsSubmit = val;
    contract();
  }
};

const handleSizeChange = (valueSise) => {
  pageSize.value = valueSise;
  contract();
};
const handleCurrentChange = (valuePage) => {
  pageNum.value = valuePage;
  contract();
};

// 导出
function exportExcelAction(val) {
  if (datetime.value && datetime.value[0]) {
    startTime.value = datetime.value[0];
  }
  if (datetime.value && datetime.value[1]) {
    endTime.value = datetime.value[1];
  }

  if (datetime.value === null) {
    startTime.value = "";
    endTime.value = "";
  }

  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    startTime: startTime.value,
    endTime: endTime.value,
    enterpriseName: enterpriseName.value,
    contractAmount: contractAmount.value,
    contractAllAmount: contractAllAmount.value,
    paymentMethod: paymentMethod.value,
    stampCount: stampCount.value,
    stampTypeList: stampTypeList.value && stampTypeList.value.join(),
  };
  if (val) {
    for (let key in val) {
      if (val[key]) {
        params[key] = val[key];
      }
    }
  }

  proxy.download(
    "/system/contract/export",
    params,
    `合同管理_${
      new Date().getFullYear() +
      "-" +
      new Date().getMonth() +
      1 +
      "-" +
      new Date().getDate()
    }.xlsx`
  );
}

const handleAdd = () => {
  router.push({
    path: "/contract/add/add",
    query: { name: "1" },
  });
};

const handleDetails = (row) => {
  router.push({
    path: "/contract/add/add",
    query: {
      name: "3",
      id: row.contractId,
    },
  });
};

const handleEdit = (row) => {
  router.push({
    path: "/contract/add/add",
    query: { name: "2", id: row.contractId },
  });
};

// 上传合同附件
const handleFile = (row) => {
  router.push({
    path: "/contract/add/add",
    query: { name: "3", id: row.contractId, contractStatus: "1" },
  });
};

// 删除
const handelDelete = (row) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row && row.contractId) {
        const result = await contractDeleteApi(row.contractId);
        if (result.code === 200) {
          // 删除成功的提示
          ElMessage.success(result.msg);
          contract();
        }
      }
    })
    .catch((err) => {
      // 用户点击取消执行的操作
      //   ElMessage.error(result.msg);
      console.log(err);
    });
};

// 撤回
const handeleRevoke = (row) => {
  ElMessageBox.confirm("确定要撤回吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row && row.contractId) {
        const result = await withdrawApi(row.contractId);
        if (result.code === 200) {
          // 删除成功的提示
          ElMessage.success(result.msg);
          contract();
        }
      }
    })
    .catch((err) => {
      // 用户点击取消执行的操作
      ElMessage.error("取消");
      // console.log('取消');
    });
};

onMounted(async () => {
  await contract();
  //   setTimeout(() => {
  //     loading.value = false;
  //   }, 500);
});
</script>


